package com.bfxy.order.service.producer;


import java.util.List;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.stereotype.Component;

@Component
public class OrderlyProducer {

    private DefaultMQProducer producer;

    public static final String NAMESERVER = "192.168.40.201:9876;192.168.40.202:9876;192.168.40.203:9876;192.168.40.204:9876;";

    public static final String PRODUCER_GROUP_NAME = "orderly_producer_group_name";

    private OrderlyProducer() {
        this.producer = new DefaultMQProducer(PRODUCER_GROUP_NAME);
        this.producer.setNamesrvAddr(NAMESERVER);
        this.producer.setSendMsgTimeout(3000);// 重試時間
        start();
    }

    public void start() {
        try {
            this.producer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }

    public void shutdown() {
        this.producer.shutdown();
    }

    /**
     * 順序發消息
     * @param messageList           發送過來的消息們
     * @param messageQueueNumber    把消息投遞到指定的Topic中的指定的messageQueue中，前面查詢的supplier_id（商戶ID）
     */
    public void sendOrderlyMessages(List<Message> messageList, int messageQueueNumber) {
        for (Message me : messageList) {
            try {
                this.producer.send(me, new MessageQueueSelector() {
                    @Override
                    public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
                        // 獲取我要投遞的那個ID
                        Integer id = (Integer) arg;
                        // 獲取第id個消息
                        return mqs.get(id);
                    }
                }, messageQueueNumber);//投遞到第messageQueueNumber個隊列中，messageQueueNumber==1就是投遞到第一個隊列中
            } catch (MQClientException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (RemotingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (MQBrokerException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}
